<?php

namespace app\admin\model\information;

use think\Model;
use traits\model\SoftDelete;
use app\common\model\InvShelvesLatest;
use think\Db;
use app\common\model\Inventory as comInventory;
use app\admin\model\Kisapi;
use app\admin\model\information\KisBaseinfo;
use app\admin\model\inventory\Wmskc;

class Inventory extends Model
{
    //use SoftDelete;
    protected $pk = 'id';
    // 表名
    protected $name = 'inventory';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'source_text',
        'qrcode',
        'qrcodeval',
        'lastest_warehouse_text',
        'lastest_shelves_text',
        'is_thumb'
    ];
    public function getIsThumbAttr($value, $data)
    {
        return true;
    }
    
    protected static $allUpdate = [];

    
    public function getSourceList()
    {
        return ['1' => __('Source 1'), ' 2' => __('Source  2')];
    }

    public function getLastestShelvesTextAttr($value, $data)
    {
        $text = '';
        if(isset($data['id'])){
            $text = InvShelvesLatest::with('shelves')->where('inv_id',$data['id'])->value('name');
        }
        return isset($text)?$text:'';
    }
    
    public function getLastestWarehouseTextAttr($value, $data)
    {
        $text = '';
        if(isset($data['id'])){
            $text = InvShelvesLatest::with('warehouse')->where('inv_id',$data['id'])->value('name');
        }
        return isset($text)?$text:'';
    }

    public function getSourceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source']) ? $data['source'] : '');
        $list = $this->getSourceList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    
    //追加二维码

    public function getQrcodeAttr($value, $data)
    {
        $domain = request()->domain();
        $list = db('shelves')->where(['id'=>$data['shelves_id']])->find();
        if(!isset($data['cBatch'])){
            $data['cBatch'] = '';
        }
        $data['qrcode']=$domain.'/index.php/qrcode/build?padding=0&text=WL'.$data['number'].'!'.$data['cBatch'];
        return $data['qrcode'];
    }

    //追加二维码val
    public function getQrcodevalAttr($value, $data)
    {
        if(isset($data['name'])){
            if(!isset($data['cBatch'])){
                $data['cBatch'] = '';
            }
            //$data['qrcode'] = $domain . '/index.php/qrcode/build?text=' . "名称:".$data['name'].'|编码:'.$data['number'];
            $data['qrcode'] =  'WL'.$data['number'].'!'.$data['cBatch'];
            return $data['qrcode'];
        }
    }

    public function warehouse(){
        return $this->hasOne('\app\admin\model\information\Warehouse','id','warehouse_id','','LEFT')->setEagerlyType(0);
    }
    
    public function shelves(){
        return $this->hasOne('\app\admin\model\information\Shelves','id','shelves_id','','LEFT')->setEagerlyType(0);
    }
    
    public function invshlatest(){
        return $this->hasOne('\app\admin\model\information\InvShelvesLatest','inv_id','id','','LEFT')->setEagerlyType(0);
    }
    
    /**
     * 同步数据
     */
    public function getInventoryData($inv_number='')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');//临时加大内存

        $conditon = ['PageSize'=>1,'PageIndex'=>1];
        if($inv_number){
            $conditon['fNumber'] = $inv_number;
        }
        
        //取物料
        $row = Kisapi::getDataByName('inventory',$conditon,true);
        
        $count = $row['data_totle'];
        $newList =[];
        if($count>1000) {
            for($i=1;$i<=(intval($count/1000)+1);$i++){
                $res = Kisapi::getDataByName('inventory',['PageSize'=>1000,'PageIndex'=>$i],true);
                $data = $res['data_item'];
                $newList = array_merge($newList,$data);
            }
        }else{
            $res = Kisapi::getDataByName('inventory',['PageSize'=>1000,'PageIndex'=>1],true);
            $newList = $res['data_item'];
        }
        
        if($newList){
            $unitArr = KisBaseinfo::getUnit(true);
            $kis_unit_coefficient = cache('kis_unit_coefficient');
            $itemClass = KisBaseinfo::getIcItemClass();
            $warehouse = KisBaseinfo::getStock();
            $data  = [];
            if(!$kis_unit_coefficient){
                exception('数据准备中,请稍后再同步');
            }
            
            foreach ($newList as $value) {
                //$unit = isset($unitArr[$value['fStockUnitId']])?str_replace('/', '|', $unitArr[$value['fStockUnitId']]):'';
                //$sec_unit = isset($unitArr[$value['fProUnitId']])?str_replace('/', '|', $unitArr[$value['fProUnitId']]):'';
                //$unit = isset($unitArr[$value['fStockUnitId']])?str_replace('/', '|', $unitArr[$value['fStockUnitId']]):'';
                //$sec_unit = isset($unitArr[$value['fProUnitId']])?str_replace('/', '|', $unitArr[$value['fProUnitId']]):'';
                $cInvCName = isset($itemClass[$value['fParentId']])?$itemClass[$value['fParentId']]:'';

                $data[] = [
                    'id' => $value['fItemId'],
                    'name' => $value['fName'],
                    'specification' => $value['fModel'],
                    'number' => $value['fNumber'],
                    //'warehouse_code'=>$value['cDefWareHouse'],
                    'classification_id' => $value['fParentId'],
                    'classification_name' => $cInvCName,
                    //'group' => $value['cGroupName'],
                    'unit' => @$unitArr[$value['fUnitID']],
                    'unit_code'=>$value['fUnitID'],
                    'store_unit' => @$unitArr[$value['fStockUnitId']],
                    'store_unit_code'=>$value['fStockUnitId'],
                    'fCoefficient' => @$kis_unit_coefficient[$value['fStockUnitId']],
                    'mbatch' => $value['fIsBatch'],
                    'fIsShelfLife' => $value['fIsShelfLife'],
                    'fShelfLife' => $value['fShelfLife'],
                    //'safe_num' => $value['iSafeNum'],
                    //'max_num' => $value['iTopSum'],
                    //'min_num' => $value['iLowSum'],
                    //'attributes' => '',//($value['cFree1']==null)?'':$value['cFree1'],
                    'shelves_id' => null,
                    'shelves_name' => '',
                    'warehouse_id' => $value['fDefaultLoc'],//物料默认仓、最新仓库
                    'default_warehouse_id' => $value['fDefaultLoc'],//金蝶物料默认仓
                    'default_warehouse_name' => isset($warehouse[$value['fDefaultLoc']])?$warehouse[$value['fDefaultLoc']]:''
                ];
                
                //手动同步，不更新最新路径
                // $tj_arr = comInventory::getTjWhShByInvNumber($value['fItemId'],'inv');
                // if(isset($tj_arr['lastest_shelves_id'])&&!empty($tj_arr['lastest_shelves_id'])){
                //     $data['shelves_id'] = $tj_arr['lastest_shelves_id'];
                //     $data['shelves_name'] = $tj_arr['lastest_shelves_name'];
                //     $data['warehouse_id'] = $tj_arr['lastest_warehouse_id'];
                //     $data['warehouse_name'] = $tj_arr['lastest_warehouse_name'];
                // }
            }
           
            if($data){
                //Inventory::saveAll($data,true);
                db('inventory')->insertAll($data,true);
            }
        }
    }
    
    //批量更新
    public static function updateAll($data,$has){
        $id = $has['id'];
        unset($data['createtime']);
        unset($has['id']);
        $result = array_diff($data,$has);
        $data['updatetime']=date('Y-m-d H:i:s',time());
        $data['id']=$id;
        $string =[];
        
        if(!empty($result)){
            foreach ($data as $v){
                if(is_string($v)) $v="'".$v."'";
                array_push($string,$v==null?'NULL':$v);
            }
            
            unset($v);
            $new_string ='('.implode(',',$string).')';
            array_push(self::$allUpdate,$new_string);
        }
    }
    
    /**
     * 构建查询
     * @return \think\db\Query
     * @throws \think\Exception
     */
    
    public static function getSql()
    {
        $sql = Db::connect('database.sec')->table('inventory')
        ->alias('i')
        ->join('computationGroup g','i.cGroupCode=g.cGroupCode')
        ->join('ComputationUnit u','i.cComunitCode=u.cComunitCode')
        ->join('InventoryClass c','i.cInvCCode =c.cInvCCode ')
        ->where([
            'i.cInvCCode' => [['like','06%'],['like','08%'], 'or']
        ])
        ->where([
            'i.cInvCCode' => ['not like','0810%']
        ])
        //->join('currentstock k','i.cInvCode = k.cInvCode','left')
        ->field('i.cDefWareHouse,i.cInvCode,i.cInvName,i.cInvStd,i.cInvCCode,i.iSafeNum,i.iTopSum,i.iLowSum,i.bInvBatch,g.cGroupName,u.cComUnitName,
            c.cInvCName,u.cComunitCode');//,k.cFree1
        
        return $sql;
    }

    public static function getInvObj($inv_number,$synkc = false){
        if(!$inv_number)return ;

        (new self())->getInventoryData($inv_number);//干啥都先更新档案
        $obj = self::get(['number'=>$inv_number]);
        if(!$obj){
            exception("存货编码:{$inv_number}有误");
        }

        if($synkc){
            //刷库存
            Wmskc::where([
                'inv_number' => $inv_number
            ])
            ->update([
                'inv_name' => $obj->getAttr('name'),
                'inv_specification' => $obj->getAttr('specification')
            ]);
        }
        
        return $obj;
    }
   
}
